import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fsharing/core/models/cart_add.dart';
import 'package:fsharing/core/models/product_detail.dart';
import 'package:fsharing/core/viewmodels/pages/store/buy_now_model.dart';
import 'package:fsharing/core/viewmodels/pages/store/cart_add_model.dart';
import 'package:fsharing/core/viewmodels/pages/store/product_detail_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/store/store_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/count_down_badge.dart';
import 'package:fsharing/ui/widgets/quantitiy_counter.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class ProductPageArgs {
  final int mId;
  final int referStoreId;

  ProductPageArgs(this.mId, this.referStoreId);
}

class ProductPage extends StatelessWidget {
  final ProductPageArgs args;

  ProductPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => ProductDetailModel(
            Provider.of(context, listen: false),
            args.mId,
            args.referStoreId,
          ),
        ),
        ChangeNotifierProvider(
          create: (context) => BuyNowModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        child: Consumer<ProductDetailModel>(
          builder: (context, value, child) {
            switch (value.viewState) {
              case ViewState.busy:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              case ViewState.error:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: Text('${value.errorMessage}'),
                  ),
                );
              case ViewState.success:
                return Scaffold(
                  body: _BodyWidget(
                    productDetail: value.productDetail,
                  ),
                  bottomNavigationBar: SafeArea(child: _BottomWidget()),
                );
              default:
                return Scaffold(
                  appBar: child,
                  body: Container(),
                );
            }
          },
          child: AppBar(
            leading: RoundBackButton(),
          ),
        ),
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final ProductDetail productDetail;

  const _BodyWidget({
    Key key,
    @required this.productDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          leading: RoundBackButton(),
          actions: <Widget>[
            IconButton(
              icon: Image.asset('assets/images/product/ic_cart.png', width: 25),
              onPressed: () {
                _onCartClicked(context);
              },
            ),
            IconButton(
              icon: Image.asset('assets/images/product/ic_menu.png', width: 25),
              onPressed: () {},
            )
          ],
          flexibleSpace: _BannerWidget(
            list: productDetail.pictures,
          ),
          expandedHeight: 375 - MediaQuery.of(context).padding.top,
        ),
        SliverToBoxAdapter(
          child: Container(
            child: CountDownBadge(
              startTime: productDetail.startTime,
              endTime: productDetail.endTime,
              serverTime: productDetail.serverTime,
              marginTop: 0,
              fontSize: 16,
            ),
          ),
        ),
        SliverToBoxAdapter(
          child: _ProductDetailWidget(
            productDetail: productDetail,
          ),
        ),
        SliverToBoxAdapter(
          child: Html(
            data: productDetail.product.detail.replaceAll(
              '<img src=\"',
              '<img src=\"https://www.lingling9.com',
            ),
          ),
        )
      ],
    );
  }

  void _onCartClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/cart');
  }
}

class _ProductDetailWidget extends StatelessWidget {
  final ProductDetail productDetail;

  const _ProductDetailWidget({
    Key key,
    @required this.productDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: 50,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Image.asset('assets/images/product/img_hot_sell.png',
                      width: 110),
                ),
              ),
              VerticalDivider(
                indent: 10,
                endIndent: 10,
                width: 24,
                thickness: 1,
                color: Colors.white,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text('灵灵九特价：', style: TextStyle(fontSize: 12)),
                  if (productDetail.originPrice != '0' &&
                      productDetail.originPrice !=
                          productDetail.validPrice.pointCoinString)
                    Text.rich(
                      TextSpan(
                        text: '原价：',
                        style: TextStyle(fontSize: 12),
                        children: [
                          TextSpan(
                            text: productDetail.originPrice,
                            style: TextStyle(
                                decoration: TextDecoration.lineThrough),
                            children: [TextSpan(text: '￥')],
                          ),
                        ],
                      ),
                    ),
                ],
              ),
              Text.rich(
                TextSpan(
                  text: productDetail.validPrice.pointCoinString,
                  style: TextStyle(fontSize: 34),
                  children: [
                    TextSpan(text: '￥', style: TextStyle(fontSize: 15)),
                  ],
                ),
              ),
              if (productDetail.validPoints.pointCoin > 0)
                Text.rich(
                  TextSpan(
                    text: productDetail.validPoints.pointCoinString,
                    style: TextStyle(fontSize: 34),
                    children: [
                      TextSpan(text: '分', style: TextStyle(fontSize: 12)),
                    ],
                  ),
                ),
            ],
          ),
        ),
        Container(
          height: 30,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  productDetail.productModelName ??
                      productDetail.product.name ??
                      '暂无商品名称',
                  style: TextStyle(fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Image.asset('assets/images/product/img_shipping.png', width: 64)
            ],
          ),
        ),
        Divider(
          height: 4,
          color: Colors.black54,
        ),
        Container(
          height: 30,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: <Widget>[
              Image.asset('assets/images/product/ic_indemnity.png', width: 12),
              SizedBox(width: 6),
              Text(
                '服务：正品保证 · 破损包换 · 极速发货',
                style: TextStyle(color: Color(0xFFA9A9A9), fontSize: 12),
              )
            ],
          ),
        ),
        Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(color: Color(0xFF535460)),
          height: 40,
          child: Text('——  宝贝详情  ——', style: TextStyle(fontSize: 15)),
        )
      ],
    );
  }
}

class _BannerWidget extends StatelessWidget {
  final List<Picture> list;

  const _BannerWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1,
      child: Swiper(
        itemBuilder: (context, index) {
          return CachedNetworkImage(
            imageUrl: list[index].url,
            fit: BoxFit.cover,
          );
        },
        itemCount: list.length,
        autoplay: true,
      ),
    );
  }
}

class _BottomWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 35, right: 7),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/product/img_bottom.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 52,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          InkWell(
            child: Image.asset('assets/images/product/ic_store.png', width: 22),
            onTap: () {
              _onStoreClicked(context);
            },
          ),
          Image.asset('assets/images/product/ic_service.png', width: 22),
          Row(
            children: <Widget>[
              InkWell(
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image:
                          AssetImage('assets/images/product/img_add_cart.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  width: 105,
                  height: 40,
                  child: Text(
                    '加入购物车',
                    style: TextStyle(color: Theme.of(context).accentColor),
                  ),
                ),
                onTap: () {
                  _onCartAddClicked(context);
                },
              ),
              Container(
                width: 105,
                child: Consumer<BuyNowModel>(
                  builder: (context, model, child) {
                    switch (model.viewState) {
                      case ViewState.busy:
                        return RaisedButton(
                          onPressed: null,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.horizontal(
                              right: Radius.circular(20),
                            ),
                          ),
                          child: SizedBox(
                            width: 14,
                            height: 14,
                            child: CircularProgressIndicator(),
                          ),
                        );
                      default:
                        return RaisedButton(
                          onPressed: () => _pushOrderConfirm(context),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.horizontal(
                              right: Radius.circular(20),
                            ),
                          ),
                          child: Text('立即购买'),
                        );
                    }
                  },
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  void _onStoreClicked(BuildContext context) {
    ProductDetailModel model = Provider.of(context, listen: false);
    var storeId = model.productDetail.store.id;
    var storeAreaId = model.productDetail.storeArea.id;
    Navigator.of(context)
        .pushNamed('/store', arguments: StorePageArgs(storeId, storeAreaId));
  }

  void _onCartAddClicked(BuildContext context) async {
    ProductDetailModel model = Provider.of(context, listen: false);
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return ChangeNotifierProvider.value(
          value: model,
          child: _BottomSheetWidget(),
        );
      },
    );
  }

  void _pushOrderConfirm(BuildContext context) async {
    ProductDetailModel productModel = Provider.of(context, listen: false);

    // 先选择类型和数量，并添加到购物车
    CartAdd cartAdd = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ChangeNotifierProvider.value(
          value: productModel,
          child: _BottomSheetWidget(),
        );
      },
    );
    if (cartAdd == null) {
      return;
    }

    // 再立即购买
    BuyNowModel buyNowModel = Provider.of(context, listen: false);
    ViewState viewState =
        await buyNowModel.buyNow(productModel.productDetail, cartAdd);
    switch (viewState) {
      case ViewState.error:
        showToast(buyNowModel.errorMessage);
        break;
      default:
        Navigator.of(context)
            .pushNamed('/order/confirm', arguments: buyNowModel.cartIdQuantity);
        break;
    }
  }
}

class _BottomSheetWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        child: Container(
          margin: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
          child: SingleChildScrollView(
            child: ChangeNotifierProvider(
              create: (context) => CartAddModel(
                Provider.of(context, listen: false),
                Provider.of(context, listen: false),
              ),
              child: Column(
                children: <Widget>[
                  _MiaInfoWidget(),
                  Divider(),
                  _OptionListWidget(),
                  _QuantityWidget(),
                  _ConfirmWidget()
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _MiaInfoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<CartAddModel>(
      builder: (context, model, child) {
        var sku = model.querySku();
        var mia = model.queryMia();
        return Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CachedNetworkImage(
                imageUrl: model.productDetail.product.picture,
                width: 120,
                height: 120,
                fit: BoxFit.cover,
              ),
            ),
            Expanded(
              child: Container(
                height: 120,
                margin: EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text.rich(
                      TextSpan(
                        text: '￥',
                        style: TextStyle(
                            color: Theme.of(context).accentColor, fontSize: 13),
                        children: [
                          TextSpan(
                            text: '${mia.coinAmount}',
                            style: TextStyle(fontSize: 22),
                          ),
                          if (mia.pointCoins > 0)
                            TextSpan(
                              text: ' 分',
                              style: TextStyle(fontSize: 12),
                              children: [
                                TextSpan(
                                  text: '${mia.pointCoins}',
                                  style: TextStyle(fontSize: 22),
                                ),
                              ],
                            )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 4),
                      child: Text(
                        '库存量：${sku.stock}',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 4),
                      child: Text(
                        '${mia.name}',
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        );
      },
    );
  }
}

class _OptionListWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<CartAddModel>(
      builder: (context, model, child) {
        var list = model.productDetail.optionList;
        return ListView.builder(
          itemBuilder: (context, index) {
            var option = list[index];
            return Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(option.name),
                  Wrap(
                    spacing: 12,
                    children: List.generate(
                      option.productOptionValues.length,
                      (index) {
                        var optionValue = option.productOptionValues[index];
                        return ChoiceChip(
                          label: Text(optionValue.value),
                          labelPadding: EdgeInsets.symmetric(horizontal: 16),
                          onSelected: model.selectable(option, optionValue)
                              ? (values) => model.toggle(option, optionValue)
                              : null,
                          selected: model.selected(option, optionValue),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(4),
                          ),
                        );
                      },
                    ),
                  )
                ],
              ),
            );
          },
          itemCount: model.productDetail.optionList.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}

class _QuantityWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text('购买数量'),
          ),
          Consumer<CartAddModel>(
            builder: (context, model, child) {
              return QuantityCounter(
                quantity: model.quantity,
                onTap: (value) => model.quantity = value,
              );
            },
          ),
        ],
      ),
    );
  }
}

class _ConfirmWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 343,
      margin: EdgeInsets.only(top: 24),
      child: Consumer<CartAddModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return RaisedButton(
                onPressed: null,
                child: SizedBox(
                  width: 14,
                  height: 14,
                  child: CircularProgressIndicator(),
                ),
              );
            default:
              return RaisedButton(
                onPressed: () => _onConfirmClicked(context),
                child: Text('确定'),
              );
          }
        },
      ),
    );
  }

  void _onConfirmClicked(BuildContext context) async {
    CartAddModel model = Provider.of(context, listen: false);
    var viewState = await model.cartAdd();
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      case ViewState.success:
        showToast('已加入购物车');
        Navigator.of(context).pop(model.data);
        break;
      default:
        showToast('加入购物车失败');
        Navigator.of(context).pop();
        break;
    }
  }
}
